package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.utils.RequestPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService ;

    @Autowired
    private IPermissionService permissionService ;


    @RequestMapping("/list")
    @RequestPermission(name="角色查询",expression = "role:list")
    public String list(Model model , QueryObject qo){
        PageInfo<Role> pageInfo = roleService.query(qo);
        model.addAttribute("pageInfo",pageInfo);
        return "role/list" ;
    }

    @RequestMapping("/delete")
    @RequestPermission(name="角色删除",expression = "role:delete")
    public String delete(Long id){
        if (id != null) {
            roleService.delete(id);
        }
        return "redirect:/role/list" ;
    }


    @RequestMapping("/input")
    public String input(Long id,Model model){
        if (id != null) {
            model.addAttribute("role",roleService.selectById(id));
            model.addAttribute("roles",roleService.selectRole(id));
        }

        List<Permission> permissions = permissionService.selectAll();
        model.addAttribute("permissions",permissions);
        return "/role/input" ;
    }

    @RequestMapping("/save")
    @RequestPermission(name="角色编辑",expression = "role:save")
    public String save(Role role , Long[] ids) {
        if (role.getId() != null) {
            roleService.updateRelation(role, ids);
        } else {
            roleService.insertRelation(role, ids);
        }
        return "redirect:/role/list";
    }
}
